﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace Project.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ResisterController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public ResisterController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        [HttpPost]
        public IActionResult PostJwt(string name, string pass)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.Name,name),
                new Claim(ClaimTypes.NameIdentifier,pass),
                new Claim("UserId","123456")
            };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
            var expires = DateTime.Now.AddDays(30);//
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: _configuration["issuer"],
                audience: _configuration["audience"],
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            //生成Token
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return Ok(new
            {
                code = 200,
                msg = "成功",
                token = jwtToken
            });
        }
    }
}
